package org.mullin.stratego.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.Cookies;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.rpc.HasRpcToken;
import com.google.gwt.user.client.rpc.ServiceDefTarget;
import com.google.gwt.user.client.rpc.XsrfToken;
import com.google.gwt.user.client.rpc.XsrfTokenService;
import com.google.gwt.user.client.rpc.XsrfTokenServiceAsync;
import com.google.gwt.user.client.ui.RootPanel;

public class StrategoEntryPoint implements EntryPoint {
	
	private LoginInfo loginInfo;
	private Presenter presenter;
	private StrategoServiceAsync strategoService;
	
	@Override
	public void onModuleLoad() {
		// setup view + presenter
		Graphics.gameImages.css().ensureInjected();
		final Graphics graphics = new Graphics();

		presenter = graphics.presenter;
		graphics.setupHandlers();
		
		RootPanel.get().add(graphics);
		
		Cookies.setCookie("JSESSIONID", "JSESSIONID", null, null, "/", false);
		XsrfTokenServiceAsync xsrf = (XsrfTokenServiceAsync) GWT.create(XsrfTokenService.class);
		((ServiceDefTarget) xsrf).setServiceEntryPoint(GWT.getModuleBaseURL() + "xsrf");

		xsrf.getNewXsrfToken(new AsyncCallback<XsrfToken>() {

			@Override
			public void onFailure(Throwable caught) {

			}

			@Override
			public void onSuccess(XsrfToken result) {
				login(result);
			}

		});
	}
	
	public void login(final XsrfToken xsrfToken) {
		// game service
		strategoService = GWT.create(StrategoService.class);
		presenter.setStrategoService(strategoService);
		
		((HasRpcToken) strategoService).setRpcToken(xsrfToken);

		LoginServiceAsync loginService = GWT.create(LoginService.class);
		((HasRpcToken) loginService).setRpcToken(xsrfToken);

		System.out.println("hostPageBaseURL=" + GWT.getHostPageBaseURL());
		loginService.login(GWT.getHostPageBaseURL(), new AsyncCallback<LoginInfo>() {

			@Override
			public void onFailure(Throwable caught) {
				System.out.println("login failed :(");
			}

			@Override
			public void onSuccess(LoginInfo result) {
				loginInfo = result;

				if (loginInfo.isLoggedIn()) {
					// logging in- display game stuff, set up callbacks for messages rec'd from server,
					// and register with server.
					presenter.login(loginInfo.getLogoutUrl(), loginInfo.getEmailAddress());
					presenter.email = loginInfo.getEmailAddress();
					presenter.setChannelId(loginInfo.getToken());
					presenter.initMultiPlayer(loginInfo);
				} else {
					// logging out- hide game stuff.
					presenter.logout(loginInfo.getLoginUrl());
				}
			}			
		});
	}
}
